export class VersionNotifierLongPoll {
    constructor(versionUrl, options = {}) {
        this.url = versionUrl;
        this.currentVersion = options.currentVersion || '';
        this.onUpdateCallback = null;
        this.isRunning = false;
        this._timeoutId = null;

        this.baseRetryDelay = options.retryDelay || 3000; // 初始重试间隔
        this.maxRetryDelay = options.maxRetryDelay || 60000; // 最大重试间隔，默认1分钟
        this.retryDelay = this.baseRetryDelay; // 当前重试间隔
    }

    start() {
        if (this.isRunning) return; // 防止重复启动
        this.isRunning = true
        this.poll()
    }

    stop() {
        this.isRunning = false
        if (this._timeoutId) {
            clearTimeout(this._timeoutId);
            this._timeoutId = null;
        }
    }

    async poll () {
        if (!this.isRunning) return
        try {
            const res = await fetch(`${this.url}?version=${this.currentVersion}`, {
                method: 'GET',
                cache: 'no-cache'
            })
            const data = await res.json()
            console.log('data', data)
            if (data.update && data.version !== this.currentVersion) {
                console.log('📢 检测到新版本：', data.version);
                this.currentVersion = data.version;
                if (this.onUpdateCallback) {
                    this.onUpdateCallback(data.version);
                } 
            }
            // 成功后重置重试间隔
            this.retryDelay = this.baseRetryDelay;
        } catch(error) {
            console.warn('长轮询失败，稍后重试:', error);
            // 失败后指数增加重试间隔（最多到最大值）
            this.retryDelay = Math.min(this.retryDelay * 2, this.maxRetryDelay);
        }
        // 无论成功与否都继续轮询
        this._timeoutId = setTimeout(() => this.poll(), this.retryDelay);
    }
    onUpdate(callback) {
        this.onUpdateCallback = callback
    }
}